package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.utils.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFAnchor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;

    @RequestMapping(value = "/list", name = "查询某个购销合同下货物的数据")
    public String findAll(String contractId, @RequestParam(defaultValue = "1", name = "page") int pageNum, @RequestParam(defaultValue = "10") int pageSize) {

//        页面中需要用到的数据：
//        1、当前购销合同下的货物数据PageInfo
//        2、用来生产货物的工厂数据 通过ctype查询
//        3、合同id，为了保存货物时关联合同

//        1、当前购销合同下的货物数据PageInfo   select * from co_contract_product where contact_id=??
        ContractProductExample example = new ContractProductExample();
        example.createCriteria().andContractIdEqualTo(contractId);
        PageInfo<ContractProduct> pageInfo = contractProductService.findAll(example, pageNum, pageSize);
        request.setAttribute("page", pageInfo);
//        2、用来生产货物的工厂数据 通过ctype查询  select * from co_factory where ctype='货物'
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);

//        3、合同id，为了保存货物时关联合同
        request.setAttribute("contractId", contractId);

        return "cargo/product/product-list";
    }

    @RequestMapping(value = "/toUpdate", name = "进入编辑购销合同下货物页面")
    public String toUpdate(String id) {
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct", contractProduct);


        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);

        return "cargo/product/product-update";
    }


    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(value = "/edit", name = "保存购销合同下货物方法")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) {
//        处理图片
        String imagePath = null;
        try {
            imagePath = fileUploadUtil.upload(productPhoto);
        } catch (Exception e) {
            System.out.println(e.getMessage());

        }
        contractProduct.setProductImage(imagePath);

        if (StringUtils.isEmpty(contractProduct.getId())) {
            contractProduct.setId(UUID.randomUUID().toString());
            contractProduct.setCompanyId(getCompanyId());
            contractProduct.setCompanyName(getCompanyName());
            contractProduct.setCreateTime(new Date());
            contractProductService.save(contractProduct);
        } else {
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractProduct.getContractId();  // 重定向到货物的列表页面
    }

    //    /cargo/contractProduct/list.do?contractId=a2d5f5d4-59a9-4e70-bd76-a30f142afd9b
    @RequestMapping(value = "/delete", name = "删除购销合同下货物方法")
    public String delete(String id, String contractId) {
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;
    }

    @RequestMapping(value = "/toImport", name = "跳转到上传货物页面")
    public String toImport(String contractId) {
        request.setAttribute("contractId", contractId);
        return "cargo/product/product-import";
    }

    @RequestMapping(value = "/import", name = "上传购销合同货物方法")
    public String importXls(String contractId, MultipartFile file) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
        XSSFSheet sheet = workbook.getSheetAt(0);
        int lastRowIndex = sheet.getLastRowNum();
        List<ContractProduct> list = new ArrayList<>();
        for (int i = 1; i <= lastRowIndex; i++) {
            XSSFRow row = sheet.getRow(i);  //获取行
            ContractProduct product = new ContractProduct(); //货物
            String factoryName = row.getCell(1).getStringCellValue();//生产厂家
            product.setFactoryName(factoryName);
            String productNo = row.getCell(2).getStringCellValue();//货号
            product.setProductNo(productNo);
            Integer cnumber = ((Double) row.getCell(3).getNumericCellValue()).intValue();//数量
            product.setCnumber(cnumber);
            String packingUnit = row.getCell(4).getStringCellValue();//包装单位(PCS/SETS)
            product.setPackingUnit(packingUnit);
            String loadingRate = row.getCell(5).getNumericCellValue() + ""; //装率
            product.setLoadingRate(loadingRate);
            Integer boxNum = ((Double) row.getCell(6).getNumericCellValue()).intValue();//数量
            product.setBoxNum(boxNum);
            Double price = row.getCell(7).getNumericCellValue(); //单价
            product.setPrice(price);
            String productDesc = row.getCell(8).getStringCellValue(); // 货物描述
            product.setProductDesc(productDesc);
            String productRequest = row.getCell(9).getStringCellValue(); // 要求
            product.setProductRequest(productRequest);
            product.setContractId(contractId); // 设置合同id
            //        新增时需要赋id
            product.setCompanyId(getCompanyId());
            product.setCompanyName(getCompanyName());
            product.setId(UUID.randomUUID().toString());  //id 赋值成一个随机id
            product.setCreateDept(getUser().getDeptId());
            product.setCreateBy(getUser().getId());
            product.setCreateTime(new Date());
//            contractProductService.save(product);
            list.add(product);
        }
        contractProductService.saveList(list); //一次性保存
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;  //重定向到列表数据
    }
}
